package com.zhiwang.planet.ui

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.webkit.*
import com.bumptech.glide.Glide
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerEntertainComponent
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.RefreshEnergyEvent
import com.zhiwang.planet.mvp.p.EntertainPresenter
import com.zhiwang.planet.mvp.v.FictionCompleteView
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.WebViewClientCallBack
import com.zhiwang.planet.widget.WebViewEx
import kotlinx.android.synthetic.main.activity_fiction_web_view.*
import org.greenrobot.eventbus.EventBus
import java.lang.Exception
import javax.inject.Inject

class FictionWebViewActivity : BaseActivity(), WebViewEx.OnScrollChangeListener, FictionCompleteView, View.OnTouchListener {

    val TAG = "FictionWebViewActivity"

    //初始url
    private var url: String = ""
    //保存每次页面跳转之后的url,默认是空，防止网页加载太慢，用户回退
    private var currUrl: String = ""

    val BOOK_TAG = "chapterid="

    var shouldCount = false

    var lastX = 0f
    var lastY = 0f

    @Inject
    lateinit var entertainPresenter: EntertainPresenter

    private val delayCountRunnable = Runnable {
        readProgressBar.pause()
    }

    private val webViewClient = object : WebViewClientCallBack {

        override fun onPageFinished(view: WebView?, url: String?) {
            if (url != null)
                currUrl = url
            toolbar.title = view?.title.toString()
            val should = view?.url.toString().contains(BOOK_TAG)
            if (should) {
                readProgressBar.start()
                timeCounterLayout.setVisible()
                stopCountDelay()
            } else {
                readProgressBar.pause()
                timeCounterLayout.setInvisible()
            }
            shouldCount = should
        }

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val url = request!!.url!!.toString()
                if (url.startsWith("alipays://")
                        || url.startsWith("weixin://wap/pay?")
                        || url.startsWith("https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?")) {
                    try {
                        val intent = Intent()
                        intent.data = Uri.parse(request.url.toString())
                        intent.action = Intent.ACTION_VIEW
                        startActivity(intent)
                    } catch (e: Exception) {
                        if (url.startsWith("alipays://"))
                            Toaster.message("未安装支付宝应用")
                    } finally {
                        return true
                    }
                }

                if (request != null) {
                    currUrl = request.url.toString()
                }
            }
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {

            if (url!!.startsWith("alipays://") || url.startsWith("weixin://wap/pay?")) {
                try {
                    val intent = Intent()
                    intent.data = Uri.parse(url)
                    intent.action = Intent.ACTION_VIEW
                    startActivity(intent)
                } catch (e: Exception) {
                    if (url.startsWith("alipays://"))
                        Toaster.message("未安装支付宝应用")
                } finally {
                    return true
                }
            }

            if (url != null) {
                currUrl = url
            }
            return super.shouldOverrideUrlLoading(view, url)
        }
    }
    private val chromeClient: WebChromeClient = object : WebChromeClient() {

        override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
            return super.onConsoleMessage(consoleMessage)
        }
    }

    companion object {
        fun load(context: Context, url: String) {
            val intent = Intent(context, FictionWebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fiction_web_view)
        setSupportActionBar(toolbar)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        url = intent.getStringExtra("KEY_URL")
        initWebView()
        loadCurrUrl()
//        swipeRefreshLayout.setOnRefreshListener { loadCurrUrl() }
        initTimeCounter()
        timeCounterLayout.setOnTouchListener(this)
        DaggerEntertainComponent.builder()
                .appComponent(getAppComponent())
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        entertainPresenter.fictionReadingCompleteView = this
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        val settings = masterWebView.webView?.settings
        settings?.javaScriptEnabled = true
        settings?.useWideViewPort = true
        settings?.domStorageEnabled = true
        settings?.textZoom = 100
        masterWebView.setRetryListener {
            loadCurrUrl()
        }
        masterWebView.webViewClientCallBack = webViewClient
        masterWebView.webView?.webChromeClient = chromeClient
        masterWebView.webView?.onScrollChangeListener = this
    }

    private fun initTimeCounter() {
        //gif
        Glide.with(this)
                .load(R.drawable.yuedujindu)
                .into(gifAnimView)
        readProgressBar.setOnCompleteListener {
            readProgressBar.pause()
            masterWebView.removeCallbacks(delayCountRunnable)
            entertainPresenter.postFictionReadingTime(180)
        }
    }

    private fun loadCurrUrl() {
        masterWebView.webView?.loadUrl(url)
    }

    override fun onScrollChange(l: Int, t: Int, oldl: Int, oldt: Int) {
        if (shouldCount) {
            readProgressBar.start()
            stopCountDelay()
        }
    }

    fun stopCountDelay() {
        val canRemove = masterWebView.removeCallbacks(delayCountRunnable)
        masterWebView.postDelayed(delayCountRunnable, BuildConfig.READING_STOP_DELAY.toLong())
    }

    override fun onFictionTimePostSuccess(s: String) {
        readProgressBar.restore()
        Toaster.message(s)
        EventBus.getDefault().post(RefreshEnergyEvent())
    }

    private var leftSpace = 0f
    private var topSpace = 0f
    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                lastX = event.rawX
                lastY = event.rawY
                leftSpace = lastX - timeCounterLayout.left - timeCounterLayout.translationX
                topSpace = lastY - timeCounterLayout.top - timeCounterLayout.translationY
            }

            MotionEvent.ACTION_MOVE -> {
                onProgressBarMove(
                        event.rawX - leftSpace - timeCounterLayout.left,
                        event.rawY - topSpace - timeCounterLayout.top)
            }

            MotionEvent.ACTION_UP -> {
                leftSpace = 0f
                topSpace = 0f
                animateToSide()

            }
        }
        return true
    }

    private fun animateToSide() {
        val tx = if (timeCounterLayout.centerX > masterWebView.width / 2) 0f else -timeCounterLayout.left.toFloat() + 12.dp
        timeCounterLayout.animate()
                .translationX(tx)
                .setDuration(200)
                .setInterpolator(AccelerateDecelerateInterpolator())
                .start()
    }

    private fun onProgressBarMove(deltaX: Float, deltaY: Float) {

        timeCounterLayout.translationX = Math.max(-timeCounterLayout.left.toFloat(), Math.min((masterWebView.width - timeCounterLayout.right).toFloat(), deltaX))
        timeCounterLayout.translationY = deltaY
    }

    override fun onSupportNavigateUp(): Boolean {
        onBack()
        return true
    }

    override fun onBackPressed() {
        onBack()
    }


    /**
     * 回退逻辑：
     * 1）小说页面没有加载完，直接回退（此时表现为 currUrl 为空），直接关掉页面
     * 2）网页链接（即 http https 开头的链接）如果可以回退则回退，同时如果是首页，那么直接关掉页面
     * 3）其余非 http https 的链接 如 qq 登录的 schema wtloginmqq 等等，直接回退上一页
     * 4）关掉页面
     */
    private fun onBack() {
        val webView = masterWebView.webView
        when {

            //currUrl还没初始化（也就是页面还没加载好用户就返回了）或者回到首页按返回直接退出
            //当前页面必须是网页包含http
            currUrl.isEmpty() -> suicideAfterTransition()

            //http https 的链接(正常网页链接)
            "https".contains(Uri.parse(currUrl).scheme ?: "") -> {
                val queryParameterNames = Uri.parse(currUrl).queryParameterNames
                //首页，直接退出
                if (currUrl === url || queryParameterNames.containsAll(setOf("wxcf", "app_channel_uid"))) suicideAfterTransition()
                else if (webView?.canGoBack() != false)
                    webView?.goBack()
                else {
                    webView.clearHistory()
                    webView.loadUrl(url)
                }
            }
            webView?.canGoBack() != false -> webView?.goBack()
            else -> suicideAfterTransition()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        readProgressBar.cancel()
    }
}


